#!/usr/bin/env python
# encoding: utf-8


from django.http import HttpResponse
from django.template import RequestContext, loader
from django.shortcuts import render

from django.http import Http404
from Apis import *
from django.utils.encoding import smart_str
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
import json
from GetApis.models import *
# from GetApis.serializers import *
from Apis import *
from Apis.GetWeather import *
from Apis.ocrImg import *
from Apis.GetIdCard import *
from Apis.GetSms import *
from Apis.GetPhoneNum import *
from Apis.tuling import *
from Apis.music import *
from urllib import urlencode
from PIL import ImageFile
import StringIO
from django.views.decorators.csrf import csrf_exempt
import os
from io import TextIOWrapper
# Create your views here.
import base64


class JSONResponse(HttpResponse):
    def __init__(self, data, **kwargs):
        encodejson = json.dumps(data, ensure_ascii=False)
        encodejson = str(encodejson.encode('utf-8'))

        content = encodejson
        kwargs['content_type'] = 'application/json'

        super(JSONResponse, self).__init__(content, **kwargs)


def index(request):
    wearher = GetWeather('beijing')

    res = wearher.getjson()
    return HttpResponse(res)


def weather(request, city):
    if city == '':
        city = '西安'
    # city='xian'
    city = city.encode('utf-8')
    Weather = GetWeather(city)

    res = Weather.getdata()
    return JSONResponse(res)


def idcard(request, id):
    idobj = GetIdCard(id)
    res = idobj.getdata()
    return JSONResponse(res)


def sms(request, content, mobile):
    content = u'test中文测试test'
    content = content.encode('utf-8')
    mobile = '18589045558'
    smsobj = GetSms(mobile, content)
    res = smsobj.getdata()
    return JSONResponse(res)


def phonenum(request, num):
    # num='18589045558'
    phoneobj = GetPhoneNum(num)
    res = phoneobj.getdata()
    return JSONResponse(res)


def tuling(request, info):
    info = info.encode('utf-8')
    tl = TuLing(info)
    res = tl.getdata()
    return JSONResponse(res)


@csrf_exempt
def OCRImage(request):
    f = request.FILES["img"]
    parser = ImageFile.Parser()
    for chunk in f.chunks():
        parser.feed(chunk)
    img = parser.close()
    BASE_DIR = os.path.join(os.path.dirname(__file__), "imgs/")

    name = '%s%s' % (BASE_DIR, f.name)
    img.save(name)

    f1 = open(name, 'rb')
    imagebyte = f1.read()
    f1.close()

    # 将字节流用BASE64编码
    imgbytes = base64.b64encode(imagebyte)
    ocr = ocrImg(imgbytes)
    content = ocr.getdata()
    jsondata = {'code': 200, 'content': content}
    return JSONResponse(jsondata)


def getMusic(request, query):
    query = query.replace(' ', '')
    query = query.encode('utf-8')

    music = Music(query)
    res = music.getData()
    return JSONResponse(res)


def getImages(request):
    imgs = []
    for root, dirs, files in os.walk(r'/var/nsa/disk/NoNameDisk/pinterest'):
        for filepath in files:
            if filepath.endswith('jpg') or filepath.endswith('jpeg') or filepath.endswith('png'):
                url = 'http://pinterest.pi.com/'
                imgs.append(url + filepath)
    return JSONResponse(imgs)

